package com.shermanzhou.springbootflowable.demo.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.flowable.bpmn.BpmnAutoLayout;
import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.UserTask;
import org.flowable.editor.language.json.converter.BpmnJsonConverter;
import org.flowable.engine.common.impl.util.io.InputStreamSource;
import org.flowable.engine.common.impl.util.io.StreamSource;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouchaoqun02
 * @date 2020-06-12 11:21
 */
public class ModelConverter {
    private static ObjectMapper objectMapper = new ObjectMapper();
    private static BpmnJsonConverter bpmnJsonConverter = new BpmnJsonConverter();
    private static BpmnXMLConverter bpmnXMLConverter = new BpmnXMLConverter();

    public static BpmnModel xmlToBpmnModel(String xml) {
        InputStream xmlStream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
        StreamSource xmlSource = new InputStreamSource(xmlStream);
        BpmnModel bpmnModel = bpmnXMLConverter.convertToBpmnModel(xmlSource, true, true, "UTF-8");

        if (CollectionUtils.isEmpty(bpmnModel.getProcesses())) {
            throw new RuntimeException("Process not exists");
        }

        return bpmnModel;
    }

    public static BpmnModel jsonToBpmnModel(String jsonModel) {
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonModel);
            return bpmnJsonConverter.convertToBpmnModel(jsonNode);
        } catch (Exception e) {
            throw new RuntimeException("convertToBpmnModel fail", e);
        }
    }

    /**
     * 采用flowable默认布局
     */
    public static  String bpmnModelToJson(BpmnModel bpmnModel){
        if (bpmnModel.getLocationMap().size() == 0) {
            BpmnAutoLayout bpmnLayout = new BpmnAutoLayout(bpmnModel);
            bpmnLayout.execute();
        }

        ObjectNode modelNode = bpmnJsonConverter.convertToJson(bpmnModel);
        return modelNode.toString();
    }

    private static  List<UserTask> getUserTasks(BpmnModel model) {
        List<Process> processes = model.getProcesses();
        if (CollectionUtils.isEmpty(processes)) {
            return new ArrayList<>();
        }
        return processes.get(0).findFlowElementsOfType(UserTask.class);
    }
}
